$(function() {
    
    /* So the header looks right with JS and no JS */
    $('#header_wrapper').css('height', '-=44px');
    $('#content_wrapper').css('top', '-=44px');
    
    attachGeneral();
});






function removeGeneral() {
    $('.select_db').unbind();
    $(window).unbind('keypress');
    $('.showJS').unbind();
    $('.hideJS').unbind();
}







function attachGeneral() {
    
    
    
    
    
    
    $('.showJS').show();
    $('.hideJS').hide();
    
    
    
    
    
    
    /**
     * Key Presses
     */
    $(window).bind('keydown', function(e) {
        /* Escape */
        if(e.keyCode == 27) {
            $('.escape_close').hide();
            
            /* Hide the loading script */
            hide_loading();
        }
    });
    
    
    
    
    
    
    $('.select_db').rightClick(function() {
        var self = $(this);
        var wrapper = self.parents('.database_node_wrapper');
        
        var html = '<div class="dbright rightmenu_wrapper" style="position: absolute; top: 0; left 10px;">';
        html += 'dddd';
        html += '</div>';
        
        wrapper.append(html).css({
            'position': 'relative'
        });
        return false;
    });
    
    
    
    
    
    
    
    /**
     * Select Tbl
     * 
     * Selects a database table
     */
    $('.select_tbl').single_double_click(function() {
        /* Update the URL */
        var title = $(this).parents('.database_node_wrapper').children('.select_db').html()+' ~ '+$(this).html();

        var objData = {
            url: $(this).attr('href'),
            csrf_test_name: $.cookie(_csrf)
        };

        $.ajax({
            type: "POST",
            url: site_url('/ajax/general/get-table/'),
            data: objData,
            dataType: 'json',
            beforeSend: function() {
                //show_loading();
            },
            success: function(json) {
                //console.log(json);
                _check_logout(json);

                //hide_loading();
            }
        });
        
        return false;
    }, function() {
        var value = $('#sql_query').val();
        /* Check if a space is required */
        if(value.match(/(\s)$/) === null) { value += ' '; }
        value += $(this).html();
        $('#sql_query').val(value);
        return false;
    });
    
    
    
    
    
    
    
    $('.select_db').click(function() {
        //$(this).parents('.database_node_wrapper').children('.openclose_icon').trigger('click');
        //return false;
    });
    
    
    
    
    
    
    
    $('.openclose_icon').click(function() {
        var tables = $(this).parents('.database_node_wrapper').children('.database_table_wrapper');
        if($(this).hasClass('open')) {
            /* Close it */
            tables.slideUp();
            $(this).removeClass('open');
        } else {
            /* Open it */
            tables.slideDown();
            $(this).addClass('open');
        }
        
        return false;
    });
    
    
    
    
    
    
    
    $('.close_connection').click(function(e) {
        confirmation($(this).attr('href'), lang('javascript_confirm_close_connection'));
        return false;
    });
    
    
    
    
    
    var connection_count = 0;
    $('#connections_inner .select_connection').each(function() {
        connection_count += 1;
    });
    
    if(connection_count > 1) {
        $('#connections_inner').sortable({
            items: ".select_connection",
            stop: function(event, ui) {

                /* Find the order */
                var order = new Array;
                var connection = '';

                $('.select_connection').each(function() {
                    connection = $(this).children('.close_connection').attr('id');
                    connection = fetch_name(connection);
                    connection = connection[1];

                    order.push(connection);
                });

                var objData = {
                    csrf_test_name: $.cookie(_csrf),
                    connections: order
                };

                $.ajax({
                    type: "POST",
                    url: site_url('/ajax/general/sort-connection/'),
                    data: objData,
                    dataType: 'json',
                    beforeSend: function() {
                        //show_loading();
                    },
                    success: function(json) {
                        //console.log(json);
                        _check_logout(json);

                        //hide_loading();
                    }
                });
            }
        });
    }
    
    
    
    
    
    
    
    $('#logout_url').click(function() {
        confirmation($(this).attr('href'), lang('javascript_confirm_logout'));
        
        return false;
    });
    
    
    
    
    
    
    $('#sql_query').focus();
    $('#sql_query').keydown(function(e) {
        if(e.keyCode == 9 && e.shiftKey) {
            /* Shift and TAB key - remove TAB */
            var position = $('#sql_query').getCursorPosition();
            var input = $('#sql_query');
            
            /* Add in the TAB */
            var value = input.val().substr(0, position -1);
            value += input.val().substr(position);
            input.val(value);
            
            /* Set the cursor position */
            input.setCursorPosition(position - 1);
            return false;
        } else if(e.keyCode == 9) {
            /* TAB key - add TAB */
            var position = $('#sql_query').getCursorPosition();
            var input = $('#sql_query');
            
            /* Add in the TAB */
            var value = input.val().substr(0, position);
            value += "\t";
            value += input.val().substr(position);
            input.val(value);
            
            /* Set the cursor position */
            input.setCursorPosition(position + 1);
            return false;
        } else if(e.keyCode == 120) {
            /* F9 key - execute query */
            $('#sql_query_exec').trigger('click');
        }
    });
    
    
    
    
    
    
    $('#sql_connection').keydown(function(e) {
        if(e.keyCode == 120) {
            /* F9 key - execute query */
            $('#sql_query_exec').trigger('click');
        }
    });
    
    
    
    
    
    /* Add JS shortcut text */
    $('#sql_query_exec').attr('title', $('#sql_query_exec').attr('value')+' (F9)');
    
    $('#sql_query_exec').single_double_click(function() {
        
        var objData = {
            database: $('#sql_connection').val(),
            query: $('#sql_query').val(),
            connection: $('#connection_id').val(),
            csrf_test_name: $.cookie(_csrf)
        };
        
        $.ajax({
            type: "POST",
            url: site_url('/ajax/general/execute-query/'),
            data: objData,
            dataType: 'json',
            beforeSend: function() {
                show_loading();
            },
            success: function(json) {
                /* Encoded so non-UTF8 characters can be carried in the table */
                
                if(_check_logout(json, false)) {
                    /* We've been logged out - save the values */
                    $.cookie(_logout_database, objData.database, { path: '/' });
                    $.cookie(_logout_query, objData.query, { path: '/' });
                    $.cookie(_logout_connection, objData.connection, { path: '/' });
                    
                    /* Logout - not the most efficient way perhaps, but the easiest way */
                    _check_logout(json);
                }
                
                $('#results_wrapper').html(base64_decode(json.table));

                hide_loading();
            }
        });
        
        return false;
    }, function() {
        $('#sql_query_exec').unbind();
        $('#sql_query_exec').trigger('click');
    });
    
    
    
    
    
    
    
    
    $('#language_select').change(function() {
        $(this).parents('form').submit();
    });

}







/**
 * Check Logout
 * 
 * Check for a login.  Returns true for
 * logout, false for logged in.
 * 
 * Unless redirect false, we redirect
 * 
 * @param object json
 * @param bool redirect
 * @return bool
 */
function _check_logout(json, redirect) {
    /* Redirect by default */
    if(redirect === undefined) { redirect = true; }
    
    if(json.logged_in !== undefined && json.logged_in === false) {
        if(redirect === true) {
            window.location.replace(window.location.pathname);
        } else {
            return true;
        }
    }
    
    /* If we get here, we have a valid login */
    return false;
}

	





/**
 * Get Cursor Position
 * 
 * Gets the cursor position
 * 
 * @return number
 */
(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);








jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
    return this.each(function(){
        var clicks = 0, self = this;
        jQuery(this).click(function(event) {
            clicks++;
            if (clicks == 1) {
                setTimeout(function() {
                    if(clicks == 1) {
                        _return = single_click_callback.call(self, event);
                    } else {
                        _return = double_click_callback.call(self, event);
                    }
                    clicks = 0;
                }, timeout || 300);
            }
            
            return false;
        });
    });
}








/**
 * Set Cursor Position
 * 
 * Puts the cursor in a given
 * position
 */
new function($) {
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
}(jQuery);










/**
 * Show Loading
 * 
 * Shows the AJAX loading screen
 */
function show_loading() {$('#_loading').show();}






 /**
  * Hide Loading
  * 
  * Hides the AJAX loading screen
  */
function hide_loading() {$('#_loading').hide();}







function style_sql_query() {
    var sql = $('#sql_query').val();
    
    var regex;
    var match;
    var replace;
    var replace_regex;
    $(arrKeywords).each(function(i, val) {
        match = '(^|\\s)('+val+')(\\s|$)';
        //match = val;
        regex = new RegExp(match, 'ig');
 
        if(regex.test(sql)) {
            replace = val;
            //console.log(sql.match(regex));
            sql = sql.replace(regex, replace);
        }
    });
    $('#sql_query').val(sql);
    //console.log(arrKeywords);
    
    //var regex = new RegExp(match, 'ig');
    
    //console.log(regex.test(sql));
    
    //var string = sql.replace(regex, newSubStr_or_function, flags)
    
    //console.log(sql);
}








/**
 * Lang
 * 
 * Get the language from the key
 * 
 * @param string key
 * @param object replace
 * @return string
 */
function lang(key, replace) {
    
    var lang = '';
    if(replace === undefined) { replace = {}; }
   
    if(_objLang[key] !== undefined) {
        lang = _objLang[key];
    }
    
    return lang;
    
}







/**
 * Remove Slash
 * 
 * Removes any excess slashes.  Identical
 * to the PHP function
 */
function remove_slash(string) {
    var match = string.match(/^(\w*)\:\/\//);
    
    if(match) {
        /* There's a legitimate double slash - keep it */
        var _return = match[0] !== undefined ? match[0] : '';
        
        string = string.substr(_return.length);
        
        _return += remove_slash(string);
        
        return _return;
        
    } else {
        /* No legitimate double slashes - get rid of them all */
        return string.replace(/(\w)?(\/\/+)/, '$1/');
    }
}







/**
 * Site URL
 * 
 * Puts the index page on.  To be used
 * when calling AJAX etc
 */
function site_url(url) {
    if(_index_page != '') {_index_page = '/'+_index_page+'/';}
    
    url = remove_slash(_site_url+'/'+_index_page+url);
    
    return url;
}






/**
 * Fetch ID
 *
 * Works on the basis that AJAX IDs are in the
 * format (name)_(id)
 *
 * @param string
 * @return array
 */
function fetch_id(string) {
    var regex = /^([a-z0-9\_]+)_(\d+)$/i;
    if(regex.test(string)) {
        var arrString = string.split(/\_/);
        var id = arrString[arrString.length - 1];

        arrString = arrString.splice(0, arrString.length - 1);

        string = arrString.join('_');

        return new Array(string, id);
    } else {
        return 0;
    }
}






/**
 * Fetch Name
 *
 * Works on the basis that AJAX IDs are in the
 * format (name)_(id).  Same as fetch_id(), but
 * the ID can be any alphanumeric character, hyphens
 * and underscores
 *
 * @param string
 * @return array
 */
function fetch_name(string) {
    var regex = /^([a-z0-9]+)_([a-z0-9\-\_]+)/i;
    if(regex.test(string)) {
        string = string.split(/\_/);
        if(string.length == 2) {
            return string;
        } else {
            var arr = new Array(string[0]);
            string.splice(0, 1);
            arr[1] = string.join('_');
            return arr;
        }
    } else {
        return 0;
    }
}









/* AJAX cache */
var ajax_cache = {};






/* Clear cache every 10 minutes */
setTimeout("ajax_clear_cache()", (1000 * 60 * 10));
function ajax_clear_cache() {
    ajax_cache = {};
    setTimeout("ajax_clear_cache()", (1000 * 60 * 10));
}






/**
 * AJAX Save Cache
 *
 * Saves the AJAX data to the cache
 *
 * @param string url
 * @param object objData
 * @param mixed value
 */
function ajax_save_cache(url, objData, value) {

    $(Object.keys(objData)).each(function(i, val) {
        url += '/';
        url += val;
        url += '/';
        url += objData[val];
    });

    ajax_cache[url] = value;

}






/**
 * AJAX Get Cache
 *
 * Retrieves data from the cache.  Returns
 * false if not in cache
 *
 * @param string url
 * @param object objData
 * @return mixed
 */
function ajax_get_cache(url, objData) {

    $(Object.keys(objData)).each(function(i, val) {
        url += '/';
        url += val;
        url += '/';
        url += objData[val];
    });

    if(ajax_cache[url] == undefined) {
        /* Return false */
        return false;
    } else {
        /* Return the cache */
        return ajax_cache[url];
    }

}











function base64_decode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
        ac = 0,
        dec = "",
        tmp_arr = [];

    if (!data) {
        return data;
    }

    data += '';

    do { // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;

        o1 = bits >> 16 & 0xff;
        o2 = bits >> 8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');

    return dec;
}







function utf8_decode (str_data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var tmp_arr = [],
        i = 0,
        ac = 0,
        c1 = 0,
        c2 = 0,
        c3 = 0;

    str_data += '';

    while (i < str_data.length) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if (c1 > 191 && c1 < 224) {
            c2 = str_data.charCodeAt(i + 1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i + 1);
            c3 = str_data.charCodeAt(i + 2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}









/**
 * Confirmation
 * 
 * Shows a confirmation dialog box
 * 
 * @param string url
 * @param string message
 * @param string title
 * @param bool redirect
 */
function confirmation(self, message, title, redirect) {
    if(title === undefined) { title = lang('js_confirm'); }
    if(redirect === undefined) { redirect = true; }
    
    $.confirm({
        'title': title,
        'message': message,
        'buttons': {
            'yes': {
                'class': 'blue',
                'name': lang('js_ok'),
                'action': function() {
                    window.location = self;
                }
            },
            'No': {
                'name': lang('js_cancel'),
                'class': 'gray'
            }
        }
    });
    
    return false;
}